package com.lc.user.express;

import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lc.user.express.app.AppContext;
import com.lc.user.express.app.AppManager;
import com.lc.user.express.httpserver.GetApiUser;
import com.lc.user.express.httpserver.GetCeshi;
import com.lc.user.express.httpserver.GetCityId;
import com.lc.user.express.httpserver.Net;
import com.lc.user.express.my.LoginActivity;
import com.lc.user.express.my.MyFragment;
import com.lc.user.express.my.MyStardandActivity;
import com.lc.user.express.ordering.OrderingFragment;
import com.lc.user.express.ordering.SelectDriverActivity;
import com.lc.user.express.ordering.SendingOrderActivity;
import com.lc.user.express.ordermanagement.OrderManagementFragment;
import com.lc.user.express.ordermanagement.OrderSendingDetailsActivity;
import com.lc.user.express.preferentialactivity.PreferentialActivityFragment;
import com.lc.user.express.utils.ExampleUtil;
import com.lc.user.express.utils.LocationUtils;
import com.lc.user.express.view.dialog.AffirmDialog;
import com.yuntongxun.ecsdk.ECDevice;
import com.yuntongxun.ecsdk.ECMessage;
import com.yuntongxun.ecsdk.im.ECTextMessageBody;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.yun.YunAction;

import org.json.JSONObject;

import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import de.greenrobot.event.EventBus;


public class MainActivity extends FragmentActivity implements View.OnClickListener {

    private static final String TAG = "JPush";
    public static final String SWICH_FRAGMENT = "com.lc.user.express.main.switch";
    private BroadcastReceiver mReceiver;
    private int tab = 1;
    private FragmentManager fragmentManager;// 用于对Fragment进行管理
    private OrderingFragment orderingFragment;
    private PreferentialActivityFragment preferentialActivityFragment;
    private OrderManagementFragment orderManagementFragment;
    private MyFragment myFragment;
    private LinearLayout ll_1, ll_2, ll_3, ll_4;
    private ImageView iv_1, iv_2, iv_3, iv_4;
    private TextView tv_1, tv_2, tv_3, tv_4;
    public static OnLoginListener onLoginListener;
    public static OnCityChanged onCityChanged = null;

    public interface OnLoginListener {
        void onLogin(boolean isLogin);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        AppContext.ScaleScreenHelper.loadView((ViewGroup) getWindow().getDecorView());
        AppManager.getAppManager().addActivity(this);
        LocationUtils.getInstance().init();
        initView(); //添加布局
        if (savedInstanceState != null) {
            setTabSelection(savedInstanceState.getInt("tab", 1));
        } else {
            setTabSelection(1);
        }
        registerReceiver();

//        if (JPushInterface.isPushStopped(MainActivity.this) && AppContext.myPreferences.getIsLogin()) {
//            Log.i("Jpush", "resumePush");
//            JPushInterface.resumePush(MainActivity.this);
//        }
//        if (!TextUtils.isEmpty(AppContext.myPreferences.getUid())) {
//            JPushInterface.setAlias(MainActivity.this, AppContext.myPreferences.getUid(), mAliasCallback);
//        }
        onCityChanged = new OnCityChanged() {
            @Override
            public void onCity(String city) {
                showCityChangeDialog(city);
            }
        };
//        ceshi();
//        setStyleBasic();

        checkVersion();

        YunAction.getInstance().initia(MainActivity.this, new ECDevice.InitListener() {

            @Override
            public void onInitialized() {

                YunAction.getInstance().setYunCallBack(new YunAction.YunCallBack() {

                    @Override
                    public void connError() {
                    }

                    @Override
                    public void loginSucceed() {
                    }

                    @Override
                    public void otherLogin() {

                        // new AlertDialog.Builder(AppManager.getAppManager().currentActivity()).setTitle("您的账号已在其他设备登录").create().show();
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        // 设置参数
                        builder.setTitle("您的账号已在其他设备登录")

                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                    // 积极

                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        dialog.dismiss();
                                    /*    MyApplication.myPreferences.clearAll();
                                        MainActivity.tuiChu.tuiChu();*/
                                        AppContext.myPreferences.setIsLogin(false);
                                        AppContext.myPreferences.setUid("");
                                        AppContext.myPreferences.setUserName("");

                                        MyFragment.riv_head.setVisibility(View.GONE);
                                        MyFragment.tv_phone.setVisibility(View.GONE);
                                        MyFragment.tv_login.setVisibility(View.VISIBLE);
                                        MyFragment.tv_public.setVisibility(View.GONE);
//                MyApplication.getInstance().finishActivity();
                                        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                                        startActivity(intent);
                                    }
                                });
                        builder.create().show();
                    }

                    @Override
                    public void onReceivedMessage(ECMessage ecMessage) {

                        if (ecMessage.getType() == ECMessage.Type.TXT) {

                            ECTextMessageBody body = (ECTextMessageBody) ecMessage.getBody();

                            int type = 0;

                            try {

                                JSONObject jsonObject = new JSONObject(body.getMessage());

                                type = jsonObject.optInt("type");

                            } catch (Exception e) {

                                e.printStackTrace();

                            }

                            if (type == 1) {

                                if (AppManager.getAppManager().currentActivity() instanceof SendingOrderActivity) {

                                    MainActivity.this.sendBroadcast(new Intent(SendingOrderActivity.SHOW_SELECT_DIVER));

                                } else if (AppManager.getAppManager().currentActivity() instanceof SelectDriverActivity) {

                                    MainActivity.this.sendBroadcast(new Intent(SelectDriverActivity.REFRESH));

                                }

                            } else if (type == 2) {

                                if (OrderManagementFragment.onRefreshOrderData != null) {

                                    OrderManagementFragment.onRefreshOrderData.onRefresh();

                                }

                                MainActivity.this.sendBroadcast(new Intent(OrderSendingDetailsActivity.SHOW_SELECT_DIVER));

                            }

                        }

                    }

                });

                if (!AppContext.myPreferences.getUid().equals("")) {

                    YunAction.getInstance().login(MainActivity.this, AppContext.myPreferences.getUid());

                }

            }

            @Override
            public void onError(Exception e) {

            }

        });

//        startActivity(new Intent(getApplicationContext(),CostActivity.class));
    }

    @SuppressLint("NewApi")
    private void initView() {
        fragmentManager = getSupportFragmentManager();
        ll_1 = (LinearLayout) findViewById(R.id.ll_1);
        ll_2 = (LinearLayout) findViewById(R.id.ll_2);
        ll_3 = (LinearLayout) findViewById(R.id.ll_3);
        ll_4 = (LinearLayout) findViewById(R.id.ll_4);
        iv_1 = (ImageView) findViewById(R.id.iv_1);
        iv_2 = (ImageView) findViewById(R.id.iv_2);
        iv_3 = (ImageView) findViewById(R.id.iv_3);
        iv_4 = (ImageView) findViewById(R.id.iv_4);
        tv_1 = (TextView) findViewById(R.id.tv_1);
        tv_2 = (TextView) findViewById(R.id.tv_2);
        tv_3 = (TextView) findViewById(R.id.tv_3);
        tv_4 = (TextView) findViewById(R.id.tv_4);
        ll_1.setOnClickListener(this);
        ll_2.setOnClickListener(this);
        ll_3.setOnClickListener(this);
        ll_4.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.ll_1) {
            tab = 1;
            setTabSelection(1);
        } else if (v.getId() == R.id.ll_2) {
            setTabSelection(2);
        } else if (v.getId() == R.id.ll_3) {
            tab = 3;
            setTabSelection(3);
        } else if (v.getId() == R.id.ll_4) {
            tab = 4;
            setTabSelection(4);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub
        super.onNewIntent(intent);

    }

    @Override
    protected void onPause() {
        super.onPause();
//        JPushInterface.onPause(MainActivity.this);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        JPushInterface.onResume(MainActivity.this);
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        LocationUtils.getInstance().recycleLocation();
        AppContext.myPreferences.setIsShowCityDialog(true);
        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
        }
//        JPushInterface.stopPush(MainActivity.this);
    }

    /**
     * 根据传入的index参数来设置选中的tab页。
     */
    @SuppressLint("NewApi")
    private void setTabSelection(int index) {
        // 开启一个Fragment事务
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        // 先隐藏掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
        switch (index) {
            case 1:
                hideFragments(transaction);
                if (orderingFragment == null) {
                    orderingFragment = new OrderingFragment();
                    transaction.add(R.id.id_content, orderingFragment);
                } else {
                    transaction.show(orderingFragment);
                }
                break;
            case 2:
                if (AppContext.myPreferences.getIsLogin()) {
                    tab = 2;
                    hideFragments(transaction);
                    if (orderManagementFragment == null) {
                        orderManagementFragment = new OrderManagementFragment();
                        transaction.add(R.id.id_content, orderManagementFragment);
                    } else {
                        transaction.show(orderManagementFragment);
                    }
                } else {
                    onLoginListener = new OnLoginListener() {
                        @Override
                        public void onLogin(boolean isLogin) {

                            if (isLogin) {
                                tab = 2;
                            }
                            setTabSelection(tab);
                            onLoginListener = null;
                        }
                    };
                    Intent i = new Intent(MainActivity.this, LoginActivity.class);
                    i.addFlags(LoginActivity.TYPE_LOGIN);
                    startActivity(i);
                }
                break;
            case 3:
                hideFragments(transaction);
                if (preferentialActivityFragment == null) {
                    preferentialActivityFragment = new PreferentialActivityFragment();
                    transaction.add(R.id.id_content, preferentialActivityFragment);
                } else {
                    transaction.show(preferentialActivityFragment);
                }
                break;
            case 4:
                hideFragments(transaction);
                if (myFragment == null) {
                    myFragment = new MyFragment();
                    transaction.add(R.id.id_content, myFragment);
                } else {
                    transaction.show(myFragment);
                }
                break;
        }
        tabButton();
//        transaction.commitAllowingStateLoss();
        transaction.commit();
    }

    /**
     * @Title: tabButton
     * @Description: TODO 底部按钮状态
     * @author Administrator
     * @date: 2015-7-22 下午4:26:08
     */
    private void tabButton() {
        tv_1.setSelected(false);
        tv_2.setSelected(false);
        tv_3.setSelected(false);
        tv_4.setSelected(false);
        iv_1.setSelected(false);
        iv_2.setSelected(false);
        iv_3.setSelected(false);
        iv_4.setSelected(false);
        if (tab == 1) {
            tv_1.setSelected(true);
            iv_1.setSelected(true);
        } else if (tab == 2) {
            tv_2.setSelected(true);
            iv_2.setSelected(true);
        } else if (tab == 3) {
            tv_3.setSelected(true);
            iv_3.setSelected(true);
        } else if (tab == 4) {
            tv_4.setSelected(true);
            iv_4.setSelected(true);
        }
    }

    /**
     * 将所有的Fragment都置为隐藏状态。
     *
     * @param transaction 用于对Fragment执行操作的事务
     */
    @SuppressLint("NewApi")
    private void hideFragments(FragmentTransaction transaction) {
        if (orderingFragment != null) {
            transaction.hide(orderingFragment);
        }
        if (orderManagementFragment != null) {
            transaction.hide(orderManagementFragment);
        }
        if (myFragment != null) {
            transaction.hide(myFragment);
        }
        if (preferentialActivityFragment != null) {
            transaction.hide(preferentialActivityFragment);
        }

    }

    @Override
    public void onAttachFragment(Fragment fragment) {
        // TODO Auto-generated method stub
        super.onAttachFragment(fragment);

        if (orderingFragment == null && fragment instanceof OrderingFragment) {
            orderingFragment = (OrderingFragment) fragment;
        } else if (orderManagementFragment == null && fragment instanceof OrderManagementFragment) {
            orderManagementFragment = (OrderManagementFragment) fragment;
        } else if (myFragment == null && fragment instanceof MyFragment) {
            myFragment = (MyFragment) fragment;
        } else if (preferentialActivityFragment == null && fragment instanceof PreferentialActivityFragment) {
            preferentialActivityFragment = (PreferentialActivityFragment) fragment;
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("tab", tab);
    }


    /**
     * 这里用到的了EventBus框架  博客教程:http://blog.csdn.net/lmj623565791/article/details/40920453
     *
     * @param type
     */
    public void onEventMainThread(Integer type) {
        Log.d("XX", "EventBus收到int:" + type);
        //  Toast.makeText(this, "处理eventbus请求",0).show();
        if (type == 0) {
            tab = 4;
            setTabSelection(4);
        } else {
            tab = 1;
            setTabSelection(1);
        }
    /*
        if(type==LOGOUT){//登出

        }else if (type==LOGOUT2){
            llMainTab02.performClick();//模拟点击首页
            secondFragment.setCurrentItem(0);//跳转到推荐页面
        }*/
    }


    @Override
    public void onBackPressed() {

        // TODO Auto-generated method stub
        AppManager.getAppManager().exitBy2Click(MainActivity.this);
    }

    private void showCityChangeDialog(final String city) {
        if (AppContext.myPreferences.getIsShowCityDialog()) {
            AffirmDialog affirmDialog = new AffirmDialog(MainActivity.this, "当前定位城市为" + city + ",是否切换？", "取消", "切换", R.style.MyDialog) {

                @Override
                protected void onYesClick() {

                    // TODO Auto-generated method stub
                    AppContext.myPreferences.setCity(city);
                    getCityId(city);
                }
            };

            affirmDialog.setOnKeyListener(keylistener);
            affirmDialog.show();

            AppContext.myPreferences.setIsShowCityDialog(false);

        }
    }

    private void getCityId(final String city) {
        new GetCityId(city, new AsyCallBack<GetCityId.Info>() {
            @Override
            public void onSuccess(String toast, int type, GetCityId.Info info) throws Exception {

                AppContext.myPreferences.setCityId(info.cityid);
                if (OrderingFragment.onCityChanged != null)
                    OrderingFragment.onCityChanged.onCityChanged(city, info.cityid);

                if (MyStardandActivity.onCityChanged != null)
                    MyStardandActivity.onCityChanged.onCityChanged(city, info.cityid);
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {

            }
        }).execute(MainActivity.this);
    }

    DialogInterface.OnKeyListener keylistener = new DialogInterface.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                return true;
            } else {
                return false;
            }
        }

    };

    private void registerReceiver() {
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (action == null) {
                    return;
                }
                if (action.equals(SWICH_FRAGMENT)) {
                    if (orderManagementFragment != null) {
                        if (OrderManagementFragment.onRefreshOrderData != null) {
                            OrderManagementFragment.onRefreshOrderData.onRefresh();
                        }
                    }
                    setTabSelection(2);
                }
            }
        };

        // 动态注册广播
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(SWICH_FRAGMENT);
        registerReceiver(mReceiver, intentFilter);
    }

    private static final int MSG_SET_ALIAS = 1001;
    private static final int MSG_SET_TAGS = 1002;


    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    Log.d(TAG, "Set alias in handler.");
                    JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mAliasCallback);
                    break;

                case MSG_SET_TAGS:
                    Log.d(TAG, "Set tags in handler.");
                    JPushInterface.setAliasAndTags(getApplicationContext(), null, (Set<String>) msg.obj, mTagsCallback);
                    break;

                default:
                    Log.i(TAG, "Unhandled msg - " + msg.what);
            }
        }
    };
    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.i(TAG, logs);
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i(TAG, logs);
                    if (ExampleUtil.isConnected(getApplicationContext())) {
                        handler.sendMessageDelayed(handler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    } else {
                        Log.i(TAG, "No network");
                    }
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e(TAG, logs);
            }

            Log.i(TAG, logs);
        }

    };
    private final TagAliasCallback mTagsCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.i(TAG, logs);
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i(TAG, logs);
                    if (ExampleUtil.isConnected(getApplicationContext())) {
                        handler.sendMessageDelayed(handler.obtainMessage(MSG_SET_TAGS, tags), 1000 * 60);
                    } else {
                        Log.i(TAG, "No network");
                    }
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e(TAG, logs);
            }

            Log.i(TAG, "==" + getApplicationContext());
        }

    };

    public interface OnCityChanged {
        void onCity(String city);
    }


    /**
     * 检测版本
     */
    private void checkVersion() {
        new GetApiUser(AppContext.curVersion, new AsyCallBack<GetApiUser.Info>() {
            @Override
            public void onSuccess(String toast, int type, final GetApiUser.Info info) throws Exception {
                super.onSuccess(toast, type, info);
                if (Double.parseDouble(AppContext.curVersion) >= info.web_v) {
//                    GetToast.useString(MainActivity.this, "亲，当前已是最新版本");
                } else {
                    new AffirmDialog(MainActivity.this, "检测到新版本，建议您立即更新?", "稍后再说", "立即更新", R.style.MyDialog) {
                        @Override
                        protected void onYesClick() {
//                            downBySystem(info.url);

                            try {
                                Intent intent = new Intent();
                                intent.setAction("android.intent.action.VIEW");
                                Uri content_url = Uri.parse(Net.Version);
                                intent.setData(content_url);
                                startActivity(intent);
                            } catch (ActivityNotFoundException e) {
                                e.printStackTrace();
                                Toast.makeText(MainActivity.this, "更新地址有误，请去应用市场下载最新版本", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }.show();
                }

            }
        }).execute(MainActivity.this);

    }

    /**
     * @param url 掉系统浏览器下载apk
     */
    private void downBySystem(String url) {
        if (!TextUtils.isEmpty(url)) {
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            Uri content_url = Uri.parse(url);
            intent.setData(content_url);
            startActivity(intent);
        }
    }

    /**
     * 测试推送
     */
    private void ceshi() {
        new GetCeshi(AppContext.myPreferences.getUid(), new AsyCallBack<GetCeshi.Info>() {
            @Override
            public void onSuccess(String toast, int type, GetCeshi.Info info) throws Exception {

            }

        }).execute(MainActivity.this);
    }
}
